using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

using Amazon.SimpleDB;
using NSimpleDB.Service.Contract;

namespace NSimpleDB.Service.Amazon.Dashboard
{
    // store dashboard data in TLS so each thread can grab the data belonging to its
    // last operation separately
    internal class SimpleDBDashboard
    {
        private readonly string id = Guid.NewGuid().ToString();
            // each dashboard needs its own id since more than one could be used in one thread due to several db instances

        public void SetResponseMetaData(string requestId, string boxUsage)
        {
            SimpleDBResponseMetaData rmd = new SimpleDBResponseMetaData(requestId, boxUsage);

            LocalDataStoreSlot rmdSlot = Thread.GetNamedDataSlot("RMD" + id);
            Thread.SetData(rmdSlot, rmd);

            LocalDataStoreSlot edSlot = Thread.GetNamedDataSlot("ED" + id);
            Thread.SetData(edSlot, null);
        }

        public ISimpleDBResponseMetaData GetResponseMetaData()
        {
            LocalDataStoreSlot rmdSlot = Thread.GetNamedDataSlot("RMD" + id);
            ISimpleDBResponseMetaData rmd = (ISimpleDBResponseMetaData)Thread.GetData(rmdSlot);
            //if (rmd == null)
            //    rmd = new SimpleDBResponseMetaData("", "");
            return rmd;
        }


        public void SetExceptionData(AmazonSimpleDBException ex)
        {
            SimpleDBExceptionData ed = new SimpleDBExceptionData(
                                                ex.ErrorCode, ex.ErrorType, 
                                                ex.Message, 
                                                ex.XML, 
                                                ex.StatusCode, 
                                                ex.RequestId, ex.BoxUsage);

            LocalDataStoreSlot edSlot = Thread.GetNamedDataSlot("ED" + id);
            Thread.SetData(edSlot, ed);

            LocalDataStoreSlot rmdSlot = Thread.GetNamedDataSlot("RMD" + id);
            Thread.SetData(rmdSlot, null);
        }

        public ISimpleDBExceptionData GetExceptionData()
        {
            LocalDataStoreSlot edSlot = Thread.GetNamedDataSlot("ED" + id);
            ISimpleDBExceptionData ed = (ISimpleDBExceptionData)Thread.GetData(edSlot);
            //if (ed == null)
            //    ed = new SimpleDBExceptionData("", "", "", "", System.Net.HttpStatusCode.NoContent, "", "");
            return ed;
        }
    }
}
